<template>
    <div style="margin-bottom: 5px;text-align: right;">
        <el-button size="small" @click="filetUpdate">更新</el-button>
        <el-button size="small" @click="reset(true)">重置</el-button>
        <el-button size="small" @click="save">保存</el-button>
    </div>
    <div class="box">
        <div class="box-l">
            <el-form :size="formList.formSet.size">
                <el-row>
                    <template v-for="(item,index) in formList.formData.mainList" :key="index">

                        <el-col :span="item.span" v-if="item.show">
                            <el-form-item :label="item.title" @click="clickSelect(item)" @dragstart="onadd(item,index)" @drop="drop(index)" @dragover="allowDrop($event)" draggable="true" :required="item.required" :class="selectData!=null&&selectData.fieldName===item.fieldName?'selectCss':'noCss'">
                                <el-input v-if="item.componentType==='text'||item.componentType==='array'" type="text" disabled />
                                <el-input v-else-if="item.componentType==='automaticText'" disabled placeholder="自动编号"></el-input>
                                <el-input v-else-if="item.componentType==='textarea'" type="textarea" disabled />
                                <el-input v-else-if="item.componentType==='list'" disabled>
                                    <template #append><el-icon><Plus /></el-icon></template>
                                </el-input>
                                <el-input v-else-if="item.componentType==='map'" disabled>
                                    <template #append><el-icon><Plus /></el-icon></template>
                                </el-input>
                                <el-date-picker
                                    v-else-if="item.componentType==='date'"
                                    type="date"
                                    placeholder="请选择"
                                    disabled
                                />
                                <el-select v-else-if="item.componentType==='down'" class="m-2" disabled placeholder="请选择">
                                    <!-- <el-option
                                        v-for="item in element.choose"
                                        :key="item.value"
                                        :label="item.title"
                                        :value="item.value"
                                        /> -->
                                </el-select>
                                <div v-else-if="item.componentType==='lable'" :style="{width:'100%',textAlign:item.direction?item.direction:'left',fontSize:item.size?item.size+'px':''}">
                                    {{item.title}}
                                </div>
                                <!-- <el-button v-else-if="item.componentType=='accessory'">附件</el-button> -->
                                <el-input  v-else-if="item.componentType=='accessory'">
                                    <template #append><el-icon><Plus /></el-icon></template>
                                </el-input>
                                <vxe-input v-else-if="item.componentType==='integer'" disabled style="width: 100%;" type="integer"></vxe-input>
                                <vxe-input v-else-if="item.componentType==='floating'" disabled style="width: 100%;" type="float"></vxe-input>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="item.lineFeed==='true'" :span="24"></el-col>
                    </template>
                </el-row>
            </el-form>
            <el-tabs
                v-model="activeNameTo"
                v-if="formList.formData.tableList==[]"
                type="card"
                class="demo-tabs"
            >
                <el-tab-pane v-for="(item,index) in formList.formData.tableList" :label="item.title" :name="index">
                    <vxe-toolbar ref="xToolbar">
                        <template #buttons>
                            <vxe-button size="mini" status="primary" content="新增"></vxe-button>
                            <vxe-button size="mini" status="primary" content="复制"></vxe-button>
                            <vxe-button size="mini" status="primary" content="清空"></vxe-button>
                            <vxe-button size="mini" status="warning" content="删除"></vxe-button>
                        </template>
                      </vxe-toolbar>
                    <vxe-table
                    :align="null"
                    border
                    :ref="setItemRef"
                    style="width:100%;"
                    keep-source
                    :scroll-x="{enabled: false}"
                    :selectCellByHeader="true"
                    :column-config="{isCurrent: true, isHover: true}"
                    @header-cell-click="(row)=>{clickColumn(row,index,item.ID)}"
                    :edit-rules="item.rules"
                    :edit-config="{trigger: 'click', mode: 'row', showUpdateStatus: true, showInsertStatus: true}"
                    :data="[]"
                    >
                        <vxe-column type="seq" width="60"></vxe-column>
                        <vxe-column v-for="(element,indexs) in item.column"  :visible="element.show" :width="element.width"  :key="element.fieldID" :field="element.fieldName" :title="element.title"></vxe-column>
                    </vxe-table>
                </el-tab-pane>
            </el-tabs>
        </div>
        <div class="box-r">
            <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane label="属性" name="first">
                    <sli :fidelLis="attributeData" :Components="Components" :model="selectData" :Fname="selectnemes" :MT="formList.formData.mainList" :TB="formList.formData.tableList" :TBindex="clickRef" v-if="selectData"></sli>
                </el-tab-pane>
                <el-tab-pane label="高级" name="second">
                    <sli :fidelLis="advanced" :model="selectData" :listData="selectmingData" v-if="selectData"></sli>
                </el-tab-pane>
                <el-tab-pane label="表单属性" name="third">
                    <sli :fidelLis="setData" :model="formList.formSet"></sli>
                </el-tab-pane>
                <el-tab-pane label="数据源" name="thirde">
                    <div style="background-color: #fff;padding: 5px;height: 600px; overflow: auto;">
                        <el-collapse v-model="activeNames" >
                            <el-collapse-item title="自定义" name="a">
                                <div class="ths">
                                    <div class="thsT" v-for="item in butList">
                                        <div>{{item.name}}</div>
                                        <div><el-button size="small" @click="addList(item)">新增</el-button></div>
                                    </div>
                                </div>
                            </el-collapse-item>
                          <el-button size="small" @click="reset(false)">更新字段</el-button>
                            <el-collapse-item title="表头" :name="0">
                                <div v-for="(item,index) in formList.formData.mainList" :key="index" style="display: flex;margin-bottom: 10px;">
                                    <div style="width: 80px;">{{item.title?item.title:item.name}}</div>
                                  <el-switch size="small" v-model="item['show']"
                                      active-text="显示"
                                      inactive-text="隐藏"
                                      :active-value="true"
                                      :inactive-value="false">
                                  </el-switch>

                                </div>
                            </el-collapse-item>
                            <el-collapse-item v-for="(item,index) in formList.formData.tableList" :title="item.title" :name="index+1" >
                                <div v-for="elements in item.column" style="display: flex;margin-bottom: 10px;">
                                    <div style="width: 80px;">{{elements.title}}</div>

                                  <el-switch size="small" v-model="elements['show']" @change="showWacth(elements,index)"
                                             active-text="显示"
                                             inactive-text="隐藏"
                                             :active-value="true"
                                             :inactive-value="false">
                                  </el-switch>
                                </div>
                            </el-collapse-item>
                        </el-collapse>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>
<script setup>
import {onMounted, ref, watch} from "vue"
    import {attributeData,setData,advanced} from "./sliJson.js"
    import sli from './sli.vue'
    import Sortable from 'sortablejs'
    import {getDS} from "/@/api/linkoo/templates/specification";
    import XEUtils from "xe-utils"
    const props = defineProps({
        data:{
            type:Object,
            required:true
        },
        tableData:{
            type:Array,
            required:true
        }
    })
    let butList = ref([{name:"标题",value:"separate"}])
    let clickRef = ref(null)
    const emits = defineEmits(["saveformCss"])
    const itemRefs = ref([])
    const setItemRef = el => {
        if (el) {
            itemRefs.value.push(el)
        }
    }
    const showWacth = (item,sun)=>{
      console.log(item.fieldDispName,item.show)
        itemRefs.value[sun].getColumns().forEach((elm)=>{
            if(elm.field===item.fieldName){
                elm.visible = item.show
            }
        })
    }
    let activeName = ref('first') //tas默认选项
    let activeNameTo = ref(0)
    let activeNames = ref(null)
    let mianfrom = ref([])//主表数据
    let timeTable = ref([])//明细表数据
    let formList = ref({formSet:{size:"small",rules:{},labelWidth:'100'},formData:[],formAdvancedSet:{}})//转化主表和明细表数据
    let selectData = ref(null)//当前选中的数据
    let selectmingData = ref([])//当前明细表数据
    let Components=ref([])
    onMounted(()=>{
      getDS(0).then(res=>{
        let d={}
        XEUtils.arrayEach(res.data.list,row=>{
          if (!d[row.ComponentType.toString()]){
            d[row.ComponentType.toString()]=[]
          }
          d[row.ComponentType.toString()].push(row)
        })
        Components.value= d
      })
    })
    watch(()=>{return props.data},(val,ovl)=>{
        // props.tableData.forEach(element => {
        //         if(element.tableType==0){
        //                 mianfrom.value.push(element)
        //         }else{
        //                 timeTable.value.push(element)
        //         }
        //     });
        //     control(mianfrom.value,timeTable.value)
        if(val.FormCode){
            formList.value=JSON.parse(val.FormCode)
        }else{
          reset(true)
        }

    })
    const reset=(dos)=>{
      mianfrom.value=[]
      timeTable.value=[]
      props.tableData.forEach(element => {
        if(element.tableType===0){
          mianfrom.value.push(element)
        }else{
          timeTable.value.push(element)
        }
      });
     control(mianfrom.value,timeTable.value,dos)
    }


    watch(
        () => formList.value,
        (newvalue, oldvalue) => {
            refresh()
        },{
            deep: true
        }
    );
    watch(
        () => selectData.value,
        (newvalue, oldvalue) => {
            refresh()
        },{
            deep: true
        }
    );
    watch(()=>{return clickRef.value},(val,ovl)=>{
        console.log(val);
        if(val==null){
            return
        }
        Sortable.create(itemRefs.value[val].$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
            handle: '.vxe-header--column',
            onEnd: (sortableEvent) => {
                console.log(sortableEvent);
            }
        })
    })
    // 表格刷新
    const refresh = ()=>{
        itemRefs.value.forEach((item)=>{
            item.refreshColumn()
        })
    }
    let additem = ref(null)
    let addsun = ref(null)
    const onadd = (item,index)=>{
        additem.value=item
        addsun.value=index
    }
    // 允许放下拖拽
    const allowDrop=(ev)=> {
      ev.preventDefault();
    }
    // 更新新增字段
    const filetUpdate = ()=>{
        let mianfrom = []
        props.tableData.forEach((element)=>{
            if(element.tableType===0){
                mianfrom.push(element)
            }else{
                timeTable.push(element)
            }
        })
        mianfrom[0].Fields.forEach((item)=>{
            let f = false
            formList.value.formData.mainList.forEach((t)=>{
                if(item.fieldName==t.fieldName){
                    f=true
                }
            })
            if(!f){
                formList.value.formData.mainList.push({title:item.fieldDispName,fieldName:item.fieldName,span:8,componentType:"text",required: false,show:true,formAdvancedSet:{}})
            }
        })
        console.log(formList.value);
    }
    // 放下
    const drop = (index)=>{
        if(addsun.value<index){
            formList.value.formData.mainList.splice(index+1,0,additem.value)
            formList.value.formData.mainList.splice(addsun.value,1)
            console.log(index);
        }else if(index===1&&addsun.value>index){
            formList.value.formData.mainList.splice(index,0,additem.value)
            formList.value.formData.mainList.splice(addsun.value+1,1)
            console.log(index);
        }else if(index===0&&addsun.value>index){
            formList.value.formData.mainList.splice(index,0,additem.value)
            formList.value.formData.mainList.splice(addsun.value+1,1)
        }else{
            formList.value.formData.mainList.splice(index,0,additem.value)
            formList.value.formData.mainList.splice(addsun.value+1,1)
        }
    }
    const control = (main,table,rest)=>{
      if(rest){
        formList.value.formData={
          mainList:[],
          tableList:[]
        }
      }

        main.forEach((item)=>{
            item.Fields.forEach((element)=>{
              if (rest){
                formList.value.formData.mainList.push(XEUtils.assign(element,{title:element.fieldDispName,span:8,componentType:"text",required: false,show:true,formAdvancedSet:{}}))
              }else{
                if(! XEUtils.find(formList.value.formData.mainList,it=>it.fieldName===element.fieldName)){
                  formList.value.formData.mainList.push(XEUtils.assign(element,{title:element.fieldDispName,span:8,componentType:"text",required: false,show:true,formAdvancedSet:{}}))
                }
              }


            })
        })
          if (rest){
            table.forEach((item)=>{
            let obj = XEUtils.assign(item,{title:item.tableTitle,column:[],ID:item.tableID,rules:{}})
            item.Fields.forEach((element)=>{
                obj.column.push(XEUtils.assign(element, {title:element.fieldDispName,span:24,width:"100",componentType:"text",required: false,show:true}))
            })
            delete obj['Fields']
            formList.value.formData.tableList.push(obj)
             })
          }else{
            XEUtils.arrayEach(table,tb=>{
            const id=  XEUtils.indexOf(formList.value.formData.tableList, item=>item.tableName===tb.tableName)
              tb.Fields.forEach((element)=>{
                if(! XEUtils.find(formList.value.formData.tableList[id],it=>it.fieldName===element.fieldName)){
                  formList.value.formData.tableList[id].push(XEUtils.assign(element,{title:element.fieldDispName,span:8,componentType:"text",required: false,show:true,formAdvancedSet:{}}))
                }
              })
            })
          }
    }
    let seName = ref(null)
    const clickSelect = (item)=>{
        selectData.value=item
        clickRef.value=null
        seName.value=item.title
        console.log(item);
    }
    let selectnemes = ref(null)
    const clickColumn = ({column},ID,tableID)=>{
        clickRef.value=ID
            formList.value.formData.tableList.forEach((item)=>{
                if(item.ID===tableID){
                    item.column.forEach((element)=>{
                        if(column.field===element.fieldName){
                            selectData.value=element
                            selectnemes.value=item.fieldName
                        }
                    })
                }
            })
            selectmingData.value=formList.value.formData.tableList[ID].column
    }
    const addList = (item)=>{
        formList.value.formData.mainList.unshift({componentType:'lable',type:0,title:'标签',span:24,size:24,direction:'left',show:true})
    }
    const save = ()=>{
        console.log(props.data);
        emits("saveformCss",formList.value)
    }
</script>
<style lang="scss" scoped>
.box{
    width: 100%;
    display: flex;
    .box-l{
        width: 70%;
        height: 100vh;
        overflow: auto;
        border:1px solid #ddd;
        box-sizing: border-box;
        padding: 5px;
    }
    .selectCss{
        border:1px solid #62aefb76;
        background-color: #62aefb76;
        padding: 5px;
        border-radius: 2px;
    }
    .noCss{
        border:1px solid #00ff0000;
        background-color: #409Eff00;
        padding: 5px;
    }
    .box-r{
        width: 30%;
        height: 100vh;
        border:1px solid #dddddd;
        border-left:none;
        box-sizing: border-box;
        padding: 5px;
    }
}
.thsT{
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #e5e5e59d;
    padding: 5px;
    margin-bottom: 3px;
}
</style>